package com.gmadmin.sysadmin.security.filter;

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.AuthorizationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.access.intercept.RequestAuthorizationContext;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.function.Supplier;

@Component
@Slf4j
public final class OpenPolicyAgentAuthorizationManager implements AuthorizationManager<RequestAuthorizationContext> {

    @Override
    public AuthorizationDecision check(Supplier<Authentication> authentication, RequestAuthorizationContext object) {
        HttpServletRequest request = object.getRequest();
        String requestURI = request.getRequestURI();
        log.info("权限判断当前请求requestURI:{}", requestURI);
        // 获取当前用户的所有权限
        List<String> elPermissions = authentication.get().getAuthorities().stream().map(GrantedAuthority::getAuthority).toList();
        // 判断当前用户的所有权限是否包含接口上定义的权限
        if(Arrays.stream(new String[]{requestURI}).anyMatch(elPermissions::contains)){
            return  new AuthorizationDecision(true);
        }
        return new AuthorizationDecision(false);
    }

}
